% function quick_cal_bcoe(el,cvd)
% % function quick_cal_bcoe(el,cvd)
% % el is the  eyelink default structure
% % cvd is Calibrate, Validate, or Driftcorrect
% if nargin<2
%     help(mfilename)
%     return
% end
clear;
close all;
clear persistent
clear global
clear mex
drawnow;

try % prometheus
    home_folder='E:\Data\Queens_fMRI\_bcoe\';
    home_folder='C:\Data\Queens_MRI\_bcoe\';
    cd(home_folder)
    wid=1; % window id #
    distance2screen=66;% cm
    screenwidth=37.7; %-ish  cm
    ecc=12;%*pixperdeg;
catch %mri stimulus computer
    home_folder='E:\_User\_bcoe\Data\';
    cd(home_folder)
    wid=1; % window id #
    distance2screen=140;% cm ~140cm
    screenwidth=45; % cm 45
    ecc=6;%*pixperdeg;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%    Global Defaults    %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
screenRect=get(0,'ScreenSize');
dphs=atan((screenwidth/2)/distance2screen)*180/pi;% degrees per half screen
pixperdeg=screenRect(3)/2/dphs; % pixels per degree

c_x=screenRect(3)/2;
c_y=screenRect(4)/2;
if any(screenRect<0)
    error('screen size has been changed after opening matlab')
end
num0dots=20;
ang=linspace(1,360,num0dots+1);ang(1)=[];
linspace(1,360,num0dots);
[X Y]=polar2cart(ang,repmat(ecc,1,num0dots));
dot_loc=[(X*pixperdeg)+c_x; (Y*pixperdeg)+c_y];% set ang&ecc to x&y based on screen size

status = Eyelink('IsConnected');
if status<1; %check for dummy mode each time.
    EYELINK('shutdown');
    if eyelink('initialize') ~= 0
        button = questdlg_offscreen('eyelink is not connecting','no EL1K','exit','DUMMY mode','DUMMY mode');
        if button(1)=='D'
            eyelink('initializedummy');
            status=-1;
        else
            disp('program exited by user')
            %status=0;
            return
        end
    end
end


cscale=255;
interval=1/1000;%ms
when=0; % how many screen refreshes to wait before flip
dontclear=0;% 0=copy buffer forward and clear buffer; 1=copy buffer forward and leave the buffer as is. 2=flip the two (fastest)
clearit=0;
leaveit=1;
toggleit=2;
dontsync=0; % 0=sync and wait; 1=sinc but don't wait; 2=neither sync nor wait
syncandwait=0;
sincnowait=1;
dontsincorwait=2;
multiflip=0;% for multi screens, bad idea

%try
Screen('Preference', 'VisualDebuglevel', 3); % 4 is default but it makes a painful white screen
[w,screenRect] = SCREEN('OpenWindow',wid,0);
oldblendfunction=Screen('BlendFunction',w);
SCREEN('TextStyle',w,1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
[oldFontName,oldFontNumber]=SCREEN(w,'TextFont','Tahoma');
SCREEN('TextSize',w,40);

el=EyelinkInitDefaults(w);
el.backgroundcolour=[0 0 0 1];
el.foregroundcolour=.8*cscale;
ListenChar(2);

%err=EyelinkDoTrackerSetup(el,el.ENTER_KEY);
%Elcamerasetup(screenRect(3), screenRect(4),32)
if status==0;
    disp('entering EyelinkDoTrackerSetup_bcoe')
    err=EyelinkDoTrackerSetup_bcoe(el);
    disp(' exiting EyelinkDoTrackerSetup_bcoe')
else
    disp(' skipped EyelinkDoTrackerSetup_bcoe')
end

[keyIsDown,secs,keyCode] = KbCheck;
while keyIsDown
    [keyIsDown,secs,keyCode] = KbCheck;
end
ListenChar(0);
tail=20;% tail length
tcolors=repmat([0 1 0 .8]*cscale,tail,1)'.* repmat(linspace(.25,1,tail),4,1);
dx=zeros(1,tail);
dy=dx;
dt=dx;
dot_size=63;%63 is max for drawdots
Screen('DrawDots', w,  dot_loc ,dot_size, .8*cscale ,[],1);
screen('flip',w,[],[],1);
Eyelink('StartRecording');
eye_used = Eyelink('EyeAvailable'); % get eye that's tracked
if eye_used == el.BINOCULAR; % if both eyes are tracked
    eye_used = el.LEFT_EYE; % use left eye
end
abs_start_time=(getsecs);%abs_start_time=getsecs
run=true;
temp=abs_start_time;
while run;
    update=false;
    ctime=getsecs-abs_start_time;
    %temp(end+1)=ctime; % for debugging

    if Eyelink('CheckRecording')~=0
        disp('Eyelink(''CheckRecording'')~=0');
        break;
    end
    if status>0
        if Eyelink( 'NewFloatSampleAvailable') > 0
            % get the sample in the form of an event structure
            evt = Eyelink( 'NewestFloatSample');
            % if we do, get current gaze position from sample
            x = evt.gx(eye_used+1); % +1 as we're accessing MATLAB array
            y = evt.gy(eye_used+1);
            if x~=el.MISSING_DATA & y~=el.MISSING_DATA & evt.pa(eye_used+1)>0 % do we have valid data and is the pupil visible?
                mx=x;
                my=y;
                if dt(end)<=ctime-1/60; %(1/60 is the refresh rate)
                    update=1;
                    %update tail data
                    dx=[dx(2:end) mx];
                    dy=[dy(2:end) my];
                    dt=[dt(2:end) ctime];
                end

            end
        end
    else
        update=1;
        [mx my]=getmouse;
        %update tail data
        dx=[dx(2:end) mx];
        dy=[dy(2:end) my];
        dt=[dt(2:end) ctime];
        WaitSecs(1/65-((getsecs-abs_start_time)-ctime)); % prevent over polling
    end
    if update % should update only once every 16&2/3 ms
        Screen('DrawDots', w,  dot_loc ,dot_size, .8*cscale ,[],2);
        in_dot=abs(mx-dot_loc(1,:))<dot_size/2 & abs(my-dot_loc(2,:))<dot_size/2;
        if any(in_dot)
            Screen('DrawDots', w,  dot_loc(:,in_dot) ,dot_size, 0 ,[],2);
        end
        Screen('DrawDots', w, [dx; dy] ,10, tcolors ,[],2);
        screen('flip',w,when,clearit,sincnowait);
        [keyIsDown,secs,keyCode] = KbCheck;
        if keyIsDown
            if keyCode(27)% ESC on pcwin
                run=0;
                screen('flip',w);
            end
        end
    end
end % while
ttext='Thank You';
[normBoundsRect, offsetBoundsRect]=Screen('TextBounds',w,ttext);
    for i=0:.6*cscale % fade in to help with light adaptation
    SCREEN('fillrect',w,[i i i]);
    SCREEN('TextStyle',w,1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
    SCREEN('DrawText',w,ttext,c_x-(normBoundsRect(3)/2),c_y-100,[0 i 0]);
    screen('flip',w,3);
end
waitsecs(1);
screen('closeall')
disp('succesful exit')
% catch
%    rethrow(lasterror)
%     shit
% end
Eyelink( 'StartSetup' );		% start setup mode
%shit